package com.mgq.netty.c11;

import com.mgq.netty.chat.message.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;

/**
 * @author MaGuangQi
 * 自定义协议:
 * 组成要素
 * 1.魔数:用来第一个时间判定接收的数据是否为无效数据包
 * 2.版本号:可以支持协议的升级
 * 3.序列化算法:消息正文到底采用哪种序列化反序列化方式:如JSON,protobuf,hessian,jdk
 * 4.指令类型:是登录,注册,单聊,群聊,..跟业务相关
 * 5.请求序号:为了双工通信,提供异步能力
 * 6.正文长度
 * 7.消息正文
 * @date 2021-12-07 09:44
 **/
@Slf4j

public class MessageCodec extends ByteToMessageCodec<Message> {

    @Override
    //编码
    protected void encode(ChannelHandlerContext ctx, Message msg, ByteBuf out) throws Exception {
        // 4个字节的魔数
        out.writeBytes(new byte[]{1,2,3,4});
        //1个字节的版本号
        out.writeByte(1);
        //1个字节的序列化算法: 0 jdk,1.json
        out.writeByte(0);
        //1个字节的指令类型
        out.writeByte(msg.getMessageType());
        //4个字节的请求序号
        out.writeInt(msg.getSequenceId());
        //5.填充1个字节,凑够16个字节
        out.writeByte(0xff);
        //正文长度
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(msg);
        byte[] bytes = bos.toByteArray();
        //长度用4个字节
        out.writeInt(bytes.length);
        //写入消息正文
        out.writeBytes(bytes);
    }

    @Override
    //解码
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        //直接从ByteBuf读取即可
        //1. 4个字节的魔数
        int magicNum = in.readInt();
        //2.version
        byte version = in.readByte();

        //3.序列化算法
        byte serializeType = in.readByte();
        //4.指令类型
        byte messageType = in.readByte();
        //5.序号id
        int sequenceId = in.readInt();
        //6.补齐的字节
        in.readByte();
        //7.长度
        int length = in.readInt();
        //8.正文
        byte[] bytes = new byte[length];
        //将正文写入到bytes中
        in.readBytes(bytes, 0, length);
        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
        Message message = (Message) ois.readObject();
        //记得将消息传递给下一个Handler处理.
        out.add(message);
        log.debug("{},{},{},{},{}",magicNum,version,serializeType,sequenceId,length);
        log.debug("message:{}",message);
    }
}
